<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>鹿鹿泽健身团课录入</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            margin-right: 15px;
            box-sizing: border-box;
        }
        .autocomplete {
            position: relative;
        }
        .autocomplete-items {
            position: absolute;
            border: 1px solid #d4d4d4;
            border-bottom: none;
            border-top: none;
            z-index: 99;
            top: 100%;
            left: 0;
            right: 0;
            max-height: 200px;
            overflow-y: auto;
        }
        .autocomplete-items div {
            padding: 10px;
            cursor: pointer;
            background-color: #fff;
            border-bottom: 1px solid #d4d4d4;
        }
        .autocomplete-items div:hover {
            background-color: #e9e9e9;
        }
        .selected-members-container {
            margin-top: 10px;
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }
        .selected-member-tag {
            background-color: #e0e0e0;
            padding: 10px;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            margin-bottom: 10px;
            width: 100%;
        }
        .member-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .member-details {
            display: inline-block;
            grid-template-columns: repeat(2, 1fr);
            gap: 5px;
            font-size: 14px;
            color: #555;
        }
        .member-detail-item {
            display: flex;
        }
        .member-detail-label {
            font-weight: bold;
            margin-right: 5px;
        }
        .selected-member-tag button {
            background: none;
            border: none;
            color: #666;
            margin-left: 5px;
            cursor: pointer;
            padding: 0;
            width: auto;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 4px;
            width: 100%;
            margin-top: 20px;
        }
        button:hover {
            background-color: #2980b9;
        }
        .hidden {
            display: none;
        }
        textarea {
            width: calc(100% - 2px);
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            box-sizing: border-box;
        }
    </style>
    <link rel="stylesheet" href="../static/css/minghu.css" type="text/css">
    <style>
        #sessionInfoBox {
            margin-bottom: 22px !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            background-color: #ededed !important;
            padding: 8px !important;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
            z-index: 1000 !important;
        }
    </style>
    <!-- 引入jQuery和jQuery UI库 -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
</head>
{% include 'show_ins_info.html' %}
<body>
    
    <div class="container">
        <h1>鹿鹿泽健身团课录入</h1>
        
        <form id="trainingForm">
            <!-- 会员选择（多选） -->
            <div class="form-group">
                <label for="memberInput">选择会员（可多选）</label>
                <div class="autocomplete">
                    <input type="text" id="memberInput" placeholder="输入会员姓名..." autocomplete="off">
                    <div id="memberAutocomplete" class="autocomplete-items hidden"></div>
                </div>
                <div id="selectedMembers" class="selected-members-container"></div>
                <input type="hidden" id="memberIds" name="memberIds">
            </div>
            
            <!-- 训练选择（多选） -->
            <div class="form-group">
                <label for="trainingInput">训练项目</label>
                <div class="autocomplete">
                    <input type="text" id="trainingInput" placeholder="..." autocomplete="off" disabled>
                    <div id="trainingAutocomplete" class="autocomplete-items hidden"></div>
                </div>
                <div id="selectedTrainings" class="selected-members-container"></div>
                <input type="hidden" id="trainingNames" name="trainingNames">
            </div>
            
            <!-- 教练选择 -->
            <div class="form-group">
                <label for="coachSelect">选择教练</label>
                <select id="coachSelect" name="coachId" required>
                    <option value="">-- 请选择教练 --</option>
                </select>
            </div>
            
            <!-- 合并后的日期时间选择 -->
            <div class="form-group">
                <label for="trainingDateTime">上课时间</label>
                <input type="datetime-local" id="trainingDateTime" name="trainingDateTime" required>
            </div>

            <!-- 消耗热量 -->
            <div class="form-group">
                <label for="caloriesBurned">消耗热量 (千卡)</label>
                <input type="number" id="caloriesBurned" name="caloriesBurned" min="0" step="1" required>
            </div>

            <!-- 上课点评 -->
            <div class="form-group">
                <label for="classComment">上课点评</label>
                <textarea id="classComment" name="classComment" rows="3"></textarea>
            </div>
            
            <!-- 提交按钮 -->
            <button type="submit">提交训练记录</button>
        </form>
    </div>

    <script src="../static/js/common.js"></script>
    <script>
        let insName;
        let insId;
        let insRole;
        // 简单的日期格式化函数
        function formatDate(dateString) {
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        }

        // 页面加载时获取所有必要数据
        document.addEventListener('DOMContentLoaded', function() {
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];


            // 使用AJAX获取会员数据
            fetchMembers();
            
            // 设置默认日期时间为北京时间下一个整点
            const now = new Date();
            // 转换为北京时间(UTC+8)
            const beijingOffset = 7 * 60 * 60 * 1000;
            const beijingTime = new Date(now.getTime() + beijingOffset);
            const nextHour = new Date(beijingTime.getTime() + 60 * 60 * 1000);
            // 格式化为datetime-local需要的格式(去掉时区信息)
            const formattedDateTime = nextHour.toISOString().slice(0, 16);
            document.getElementById('trainingDateTime').value = formattedDateTime;
        });

        // 使用AJAX获取所有必要数据
        function fetchMembers() {
            // 并行获取所有数据
            Promise.all([
                // fetch('/get_template_info').then(r => r.json()),
                fetch('/get_ins_list').then(r => r.json()),
                fetch('/get_group_cus_list').then(r => r.json()),
                fetch('/get_train_list').then(r => r.json())
            ])
            .then(([coachData, memberData,trainData]) => {
                // console.log('API responses:', {coachData, memberData,trainData});

                // 转换对象为数组并存储数据
                window.memberData = memberData.data && typeof memberData.data === 'object' 
                    ? Object.values(memberData.data) 
                    : [];
                window.coachData = Array.isArray(coachData.ins_list) ? coachData.ins_list : [];
                
                // 初始化训练数据
                window.trainingData = Object.keys(trainData.by_action_name).map(key => {
                    return {
                        name: key,
                        category: trainData.by_action_name[key][0],
                        muscle: trainData.by_action_name[key][1],
                        equipment: trainData.by_action_name[key][2]
                    };
                });

                // 立即初始化默认训练项目
                initDefaultTraining();
                
                console.log('Loaded data:', {
                    memberData: window.memberData,
                    trainingData: window.trainingData,
                    coachData: window.coachData
                });
                
            // 根据角色处理教练选择框
            const coachSelect = document.getElementById('coachSelect');
            const coachGroup = document.querySelector('.form-group:nth-child(3)');
            if (insRole === 'admin') {
                // 管理员显示教练选择框并填充数据
                window.coachData.forEach(coach => {
                    const option = document.createElement('option');
                    option.value = coach.slice(0,8);
                    option.textContent = coach.slice(8,);
                    if(option.value!=='LZINS999'){
                        coachSelect.appendChild(option);
                    }
                });
            } else if (insRole === 'ins') {
                // 教练隐藏教练选择框并移除required属性
                coachGroup.style.display = 'none';
                coachSelect.removeAttribute('required');
            }
                

                // 获取训练项目数据
                fetch('/get_train_list')
                .then(response => response.json())
                .then(data => {
                    // console.log('train data：',data)
                    window.trainingData = Object.keys(data.by_action_name).map(key => {
                        return {
                            name: key,
                            category: data.by_action_name[key][0],
                            muscle: data.by_action_name[key][1],
                            equipment: data.by_action_name[key][2]
                        };
                    });

                    // 初始化默认训练项目
                    initDefaultTraining();
                })
                .catch(error => {
                    console.error('获取训练数据失败:', error);
                    window.trainingData = [];
                });

                // 设置自动完成功能
                setupMemberAutocomplete();
                setupTrainingAutocomplete();
            })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    alert('获取数据失败，请刷新页面重试');
                    // 清空数据
                    window.memberData = [];
                    window.trainingData = [];
                    window.coachData = [];
                    
                    // 清空教练下拉菜单
                    const coachSelect = document.getElementById('coachSelect');
                    coachSelect.innerHTML = '<option value="">-- 请选择教练 --</option>';
                    
                    // 禁用表单输入
                    document.getElementById('memberInput').disabled = true;
                    document.getElementById('trainingInput').disabled = true;
                    document.getElementById('coachSelect').disabled = true;
                });
        }

        // 设置会员自动完成功能（支持多选）
        function setupMemberAutocomplete() {
            const input = document.getElementById('memberInput');
            const autocomplete = document.getElementById('memberAutocomplete');
            const selectedMembersContainer = document.getElementById('selectedMembers');
            const memberIdsInput = document.getElementById('memberIds');
            
            // 存储已选会员 - 声明为全局变量
            window.selectedMembers = [];
            
            input.addEventListener('input', function() {
                const val = this.value.trim();
                autocomplete.innerHTML = '';
                
                if (!val) {
                    autocomplete.classList.add('hidden');
                    return;
                }
                
                // 确保memberData是数组且有name属性
                const matches = Array.isArray(window.memberData) 
                    ? window.memberData.filter(item => 
                        item?.cus_id && item?.cus_name && (item?.cus_id+item?.cus_name).includes(val) && parseFloat(item?.cls_qty_remain)>0 &&
                        !window.selectedMembers.some(m => m.cus_id === item.cus_id)
                    )
                    : [];
        
                if (matches.length === 0) {
                    autocomplete.classList.add('hidden');
                    return;
                }
                
                // 显示匹配项
                matches.forEach(item => {
                    const itemDiv = document.createElement('div');
                    itemDiv.textContent = `${item.cus_id}${item.cus_name}`;
                    itemDiv.addEventListener('click', function() {
                        // 添加选中的会员
                        window.selectedMembers.push(item);
                        updateSelectedMembers();
                        input.value = '';
                        autocomplete.classList.add('hidden');
                    });
                    autocomplete.appendChild(itemDiv);
                });
                
                autocomplete.classList.remove('hidden');
            });
            
            // 更新已选会员显示
            function updateSelectedMembers() {
                selectedMembersContainer.innerHTML = '';
                const memberIds = [];
                
                window.selectedMembers.forEach((member, index) => {
                    const tag = document.createElement('div');
                    tag.className = 'selected-member-tag';
                    tag.innerHTML = `
                        <div class="member-name">
                            ${(index + 1).toString().padStart(2, '0')} - ${member.cus_id} ${member.cus_name}
                            <button type="button" data-index="${index}" style="float: right;">&times;</button>
                        </div>
                        <div class="member-details">
                            <div class="member-detail-item">
                                <span class="member-detail-label">卡号:</span>
                                <span>${member.card_id || '无'}</span>
                            </div>
                            <div class="member-detail-item">
                                <span class="member-detail-label">剩余节数:</span>
                                <span>${member.cls_qty_remain ? Math.floor(member.cls_qty_remain) : '0'}</span>
                            </div>
                            <div class="member-detail-item">
                                <span class="member-detail-label">到期时间:</span>
                                <span>${member.end_time ? formatDate(member.end_time) : '无'}</span>
                            </div>
                     
                        </div>
                    `;
                    tag.style.backgroundColor='#e1eff2';
                    selectedMembersContainer.appendChild(tag);
                    memberIds.push(member.cus_id);
                });
                
                // 更新隐藏的表单字段
                memberIdsInput.value = memberIds.join(',');
                
                // 添加删除按钮事件
                document.querySelectorAll('.selected-member-tag button').forEach(button => {
                    button.addEventListener('click', function() {
                        const index = parseInt(this.getAttribute('data-index'));
                        selectedMembers.splice(index, 1);
                        updateSelectedMembers();
                    });
                });
            }
            
            // 点击页面其他位置时隐藏自动完成
            document.addEventListener('click', function(e) {
                if (e.target.id !== 'memberInput') {
                    autocomplete.classList.add('hidden');
                }
            });
        }

        // 全局存储已选训练项目 - 初始化为空数组
        let selectedTrainings = [];

        // 初始化默认训练项目
        function initDefaultTraining() {
            if (!window.trainingData) return;
            
            const defaultTraining = window.trainingData.find(item => item.name === '小团课训练');
            // console.log('Initializing default training:', defaultTraining);
            if (defaultTraining) {
                selectedTrainings = [defaultTraining];
                // console.log('Default training initialized:', selectedTrainings);
                updateSelectedTrainings();
            } else {
                console.warn('"小团课训练"项目未找到');
            }
        }

        // 更新已选训练项目显示
        function updateSelectedTrainings() {
            const selectedContainer = document.getElementById('selectedTrainings');
            const trainingNamesInput = document.getElementById('trainingNames');
            
            if (selectedContainer && trainingNamesInput) {
                selectedContainer.innerHTML = '';
                
                selectedTrainings.forEach((training, index) => {
                    const tag = document.createElement('div');
                    tag.className = 'selected-member-tag';
                    tag.innerHTML = `
                        <div class="member-name">
                            ${training.name}
                            ${training.name !== '小团课训练' ? `<button type="button" data-index="${index}" style="float: right;">&times;</button>` : ''}
                        </div>
                    `;
                    tag.style.backgroundColor='#fff1e3';
                    selectedContainer.appendChild(tag);
                });
                
                // 更新隐藏的表单字段
                trainingNamesInput.value = JSON.stringify(selectedTrainings);
                
                // 添加删除按钮事件
                document.querySelectorAll('#selectedTrainings button').forEach(button => {
                    button.addEventListener('click', function() {
                        const index = parseInt(this.getAttribute('data-index'));
                        selectedTrainings.splice(index, 1);
                        updateSelectedTrainings();
                    });
                });
            }
        }

        // 设置训练自动完成功能（支持多选）
        function setupTrainingAutocomplete() {
            const input = document.getElementById('trainingInput');
            const autocomplete = document.getElementById('trainingAutocomplete');
            
            input.addEventListener('input', function() {
                const val = this.value.trim();
                autocomplete.innerHTML = '';
                
                if (!val) {
                    autocomplete.classList.add('hidden');
                    return;
                }
                
                // 过滤匹配项（排除已选项目）
                const matches = window.trainingData.filter(item => 
                    item.name.includes(val) && 
                    !selectedTrainings.some(t => t.name === item.name)
                );
                
                if (matches.length === 0) {
                    autocomplete.classList.add('hidden');
                    return;
                }
                
                // 显示匹配项
                matches.forEach(item => {
                    const itemDiv = document.createElement('div');
                    itemDiv.textContent = item.name;
                    itemDiv.addEventListener('click', function() {
                        // 添加选中的训练项目
                        selectedTrainings.push(item);
                        updateSelectedTrainings();
                        input.value = '';
                        autocomplete.classList.add('hidden');
                    });
                    autocomplete.appendChild(itemDiv);
                });
                
                autocomplete.classList.remove('hidden');
            });
            
            
            // 点击页面其他位置时隐藏自动完成
            document.addEventListener('click', function(e) {
                if (e.target.id !== 'trainingInput') {
                    autocomplete.classList.add('hidden');
                }
            });
        }

        // 表单提交处理
        document.getElementById('trainingForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 验证必填字段
            const memberIds = document.getElementById('memberIds').value;
            let coachId = insRole === 'ins' ? insId : document.getElementById('coachSelect').value;
            const trainingDateTime = document.getElementById('trainingDateTime').value;
            
            const trainingNames = JSON.parse(document.getElementById('trainingNames').value);
            
            // 特殊处理教练ID验证
            if (insRole === 'ins') {
                if (!memberIds || !trainingNames || !trainingDateTime) {
                    alert('请填写所有必填字段！');
                    return;
                }
            } else {
                if (!memberIds || !trainingNames || !coachId || !trainingDateTime) {
                    alert('请填写所有必填字段！');
                    return;
                }
            }
            
            // 准备确认信息
            const memberNames = window.selectedMembers ? 
                window.selectedMembers.map(m => m.cus_name).join(', ') : 
                '无会员';
            const trainingNamesList = Array.isArray(trainingNames) ? 
                trainingNames.map(t => t.name).join(', ') : 
                '无训练项目';
            
            // Find coach name from coachData
            const coach = window.coachData.find(c => c.slice(0,8) === coachId);
            const coachName = coach ? coach.slice(8) : coachId;

            // Format datetime to replace 'T' with space
            const formattedDateTime = trainingDateTime.replace('T', ' ');
            
            const caloriesBurned = document.getElementById('caloriesBurned').value;
            const classComment = document.getElementById('classComment').value;
            
            const confirmMsg = `即将提交以下训练记录：
            
会员姓名: ${memberNames}
训练项目: ${trainingNamesList}
上课时间: ${formattedDateTime}
教练姓名: ${coachName}
消耗热量: ${caloriesBurned} 千卡
上课点评: ${classComment || '无'}

请确认信息是否正确？`;
            
            if (!confirm(confirmMsg)) {
                return;
            }
            
            // 准备提交数据
            const formData = {
                members: window.selectedMembers.map(m => ({
                    id: m.cus_id,
                    name: m.cus_name,
                    card_id: m.card_id
                })),
                trainings: trainingNames,
                coach: {
                    id: insRole === 'admin' ? coachId : insId,
                    name: coachName
                },
                opr_id: insId,
                trainingDateTime: trainingDateTime,
                caloriesBurned: document.getElementById('caloriesBurned').value,
                classComment: document.getElementById('classComment').value
            };
            
            console.log(formData);
            // 使用AJAX提交数据
            fetch('/deal_group_class', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if(data.res==='ok'){
                    alert('训练记录提交成功！');
                    // 重置表单
                    document.getElementById('trainingForm').reset();
                    document.getElementById('selectedMembers').innerHTML = '';
                    document.getElementById('memberIds').value = '';
                    document.getElementById('selectedTrainings').innerHTML = '';
                    document.getElementById('trainingNames').value = '';
                    
                    // 重置默认日期时间为北京时间下一个整点
                    const now = new Date();
                    const beijingOffset = 7 * 60 * 60 * 1000;
                    const beijingTime = new Date(now.getTime() + beijingOffset);
                    const nextHour = new Date(beijingTime.getTime() + 60 * 60 * 1000);
                    const formattedDateTime = nextHour.toISOString().slice(0, 16);
                    document.getElementById('trainingDateTime').value = formattedDateTime;
                    window.location.replace('./');
                }else{
                    console.log(data.error);
                    window.location.replace('./');
                }
                
            })
            .catch(error => {
                console.error('提交失败:', error);
                alert('提交失败，请重试！');
                window.location.replace('./');
            });
        });
    </script>
</body>
</html>
